package com.codding.springboot_mybatisdemo.controller;

import com.codding.springboot_mybatisdemo.entity.Admin;
import com.codding.springboot_mybatisdemo.entity.Users;
import com.codding.springboot_mybatisdemo.service.AdminService;
import com.codding.springboot_mybatisdemo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/adminController")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;

    @RequestMapping("/goLogin")
    public String goLogin(Model model) {
        // 清除可能存在的错误信息，防止页面加载时显示
        model.addAttribute("errorMsg", "");
        return "login";
    }


    @RequestMapping("/doLogin")
    public String doLogin(Admin admin, Model model) {
        Admin admin1 = adminService.login(admin);
        if (admin1 != null) {
            // 登录成功，跳转到首页
            List<Users> users = userService.selectAll();
            model.addAttribute("userList", users);
            return "select";
        } else {
            // 登录失败，返回登录页面，并显示错误信息
            model.addAttribute("errorMsg", "账号或密码错误！");
            return "login";
        }
    }


    @RequestMapping("/goRegister")
    public String goRegister(){
        return "register";
    }
    @RequestMapping("/doRegister")
    public String doRegister(String username, String password, String confirmPassword, boolean check,Model model){
        int register = adminService.register(username, password, confirmPassword, check);
        if (register == 0){
            //添加失败
            model.addAttribute("errorMsg","注册失败");
            return "register";
        }else if (register == 1){
            //添加成功
            return "login";
        }else if (register == 2){
            model.addAttribute("errorMsg","请先勾选协议");
            return "register";
        }else if (register == 3){
            model.addAttribute("errorMsg","两次密码不一致");
            return "register";
        }else if (register == 4){
            model.addAttribute("errorMsg","账户已存在");
            return "register";
        }else {
            model.addAttribute("errorMsg","未知错误");
            return "register";
        }
//        return "register";
//        return null;
    }

}
